import React, { useMemo, useState, useEffect, useRef } from 'react';
import './DigitalMap.css';
import { createPortal } from 'react-dom';
interface Node {
  id: string;
  name: string;
  status: 'normal' | 'warning' | 'error';
  timestamp: string;
}

const RowContent = ({ children }: { children: React.ReactNode }) => {
  return (
    <div className="row">
      {children}
    </div>
  )
}

const DigitalMap: React.FC<{ deviceStatus: any }> = ({ deviceStatus = {} }) => {
  const { techList = [],
    globalDevice = []
  } = deviceStatus || {}
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [currentId, setCurrentId] = useState<string>('');
  const [scale, setScale] = useState(1); // 缩放比例
  const [position, setPosition] = useState({ x: 0, y: 0 }); // 内容位置
  const contentRef = useRef<HTMLDivElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const [lastTouch, setLastTouch] = useState({ x: 0, y: 0 });
  const [touchDistance, setTouchDistance] = useState<number | null>(null);

  const handleZoomIn = () => {
    setScale(prevScale => Math.min(prevScale + 0.1, 2)); // 限制最大缩放到2倍
  };

  const handleZoomOut = () => {
    setScale(prevScale => Math.max(prevScale - 0.1, 0.5)); // 限制最小缩放到0.5倍
  };

  const handleMove = (direction: 'up' | 'down' | 'left' | 'right') => {
    const step = 50; // 移动步长
    setPosition(prev => {
      switch (direction) {
        case 'up':
          return { ...prev, y: prev.y + step };
        case 'down':
          return { ...prev, y: prev.y - step };
        case 'left':
          return { ...prev, x: prev.x + step };
        case 'right':
          return { ...prev, x: prev.x - step };
        default:
          return prev;
      }
    });
  };

  // 添加复位功能
  const handleReset = () => {
    setScale(1);
    setPosition({ x: 0, y: 0 });
  };

  // 修改处理拖动开始的判断逻辑，让拖动更加智能
  const handleMouseDown = (e: React.MouseEvent) => {
    // 检查是否点击在可交互元素上
    const target = e.target as HTMLElement;

    // 如果点击的是控制按钮或提示框，不启动拖动
    if (target.closest('.control-btn, .tooltip, .module, .submodule, .bar')) {
      return;
    }

    // 设置拖动状态和起始位置
    setIsDragging(true);
    setDragStart({
      x: e.clientX - position.x,
      y: e.clientY - position.y
    });

    // 设置抓取光标
    document.body.style.cursor = 'grabbing';
  };

  // 添加触摸事件支持
  const handleTouchStart = (e: React.TouchEvent) => {
    // 检查是否触摸在可交互元素上
    const target = e.target as HTMLElement;

    if (target.closest('.control-btn, .tooltip, .module, .submodule, .bar')) {
      return;
    }

    // 阻止默认行为，防止滚动
    e.preventDefault();

    if (e.touches.length === 2) {
      // 双指触摸，准备缩放
      const dist = getDistanceBetweenTouches(e);
      setTouchDistance(dist);
    } else if (e.touches.length === 1) {
      // 单指触摸，准备拖动
      const touch = e.touches[0];
      setIsDragging(true);
      setDragStart({
        x: touch.clientX - position.x,
        y: touch.clientY - position.y
      });

      setLastTouch({
        x: touch.clientX,
        y: touch.clientY
      });
    }
  };

  // 计算两个触摸点之间的距离
  const getDistanceBetweenTouches = (e: React.TouchEvent | TouchEvent) => {
    if (e.touches.length < 2) return 0;

    const dx = e.touches[0].clientX - e.touches[1].clientX;
    const dy = e.touches[0].clientY - e.touches[1].clientY;
    return Math.sqrt(dx * dx + dy * dy);
  };

  // 处理触摸移动
  const handleTouchMove = (e: React.TouchEvent) => {
    // 阻止默认行为，防止滚动
    e.preventDefault();
    if (e.touches.length === 2 && touchDistance !== null) {
      // 双指触摸，处理缩放
      const newDistance = getDistanceBetweenTouches(e);
      const scaleFactor = newDistance / touchDistance;

      // 更新缩放值，但限制缩放范围
      setScale(prevScale => {
        const newScale = prevScale * scaleFactor;
        return Math.max(0.5, Math.min(2, newScale));
      });

      // 更新距离基准
      setTouchDistance(newDistance);
    } else if (e.touches.length === 1 && isDragging) {
      // 单指触摸，处理拖动
      const touch = e.touches[0];
      console.log('touch', touch)
      console.log('dragStart', dragStart)
      setPosition({
        x: touch.clientX - dragStart.x,
        y: touch.clientY - dragStart.y
      });

      setLastTouch({
        x: touch.clientX,
        y: touch.clientY
      });
    }
  };

  // 处理触摸结束
  const handleTouchEnd = (e: React.TouchEvent) => {
    if (e.touches.length < 2) {
      // 如果剩余触摸点少于2个，重置触摸距离
      setTouchDistance(null);
    }

    if (e.touches.length === 0) {
      // 如果没有剩余触摸点，结束拖动
      setIsDragging(false);
    }
  };

  // 处理拖动过程
  const handleMouseMove = (e: React.MouseEvent) => {
    const target = e.target as HTMLElement;
    const id = target.dataset.id;

    // 只在有id的元素上设置currentId和鼠标位置
    if (id) {
      setCurrentId(id);
      setMousePosition({
        x: e.clientX,
        y: e.clientY
      });
    }

    // 处理拖动
    if (isDragging) {
      setPosition({
        x: e.clientX - dragStart.x,
        y: e.clientY - dragStart.y
      });
    }
  };

  // 处理拖动结束时恢复光标
  const handleMouseUp = () => {
    if (isDragging) {
      setIsDragging(false);
      document.body.style.cursor = 'default';
    }
  };

  // 添加全局事件处理
  useEffect(() => {
    // 鼠标事件处理
    const handleGlobalMouseUp = () => {
      if (isDragging) {
        setIsDragging(false);
        document.body.style.cursor = 'default';
      }
    };

    const handleGlobalMouseMove = (e: MouseEvent) => {
      if (isDragging) {
        let y = e.clientY - dragStart.y
        if (y < -500) y = -500
        if (y > 500) y = 500

        setPosition({
          x: e.clientX - dragStart.x,
          y
        });
      }
    };

    console.log('po', position)

    // 触摸事件处理
    const handleGlobalTouchEnd = (e: TouchEvent) => {
      if (e.touches.length < 2) {
        // 如果剩余触摸点少于2个，重置触摸距离
        setTouchDistance(null);
      }

      if (e.touches.length === 0) {
        setIsDragging(false);
      }
    };

    const handleGlobalTouchMove = (e: TouchEvent) => {
      if (e.touches.length === 2 && touchDistance !== null) {
        // 双指触摸，处理缩放
        const newDistance = getDistanceBetweenTouches(e);
        const scaleFactor = newDistance / touchDistance;

        // 更新缩放值，但限制缩放范围
        setScale(prevScale => {
          const newScale = prevScale * scaleFactor;
          return Math.max(0.5, Math.min(2, newScale));
        });

        // 更新距离基准
        setTouchDistance(newDistance);
      } else if (e.touches.length === 1 && isDragging) {
        // 单指触摸，处理拖动
        const touch = e.touches[0];
        console.log('touch', touch)
        console.log('dragStart', dragStart)
        setPosition({
          x: touch.clientX - dragStart.x,
          y: touch.clientY - dragStart.y
        });
      }
    };

    // 添加全局事件监听
    // document.addEventListener('mouseup', handleGlobalMouseUp);
    // document.addEventListener('mousemove', handleGlobalMouseMove);
    // document.addEventListener('touchend', handleGlobalTouchEnd);
    // document.addEventListener('touchmove', handleGlobalTouchMove, { passive: false });

    // return () => {
    //   document.removeEventListener('mouseup', handleGlobalMouseUp);
    //   document.removeEventListener('mousemove', handleGlobalMouseMove);
    //   document.removeEventListener('touchend', handleGlobalTouchEnd);
    //   document.removeEventListener('touchmove', handleGlobalTouchMove);
    // };
  }, [isDragging, dragStart, touchDistance]);

  // 添加点击事件监听器，点击其他区域关闭tooltip
  useEffect(() => {
    const handleDocumentClick = (e: MouseEvent) => {
      // 如果当前有tooltip显示
      if (currentId) {
        const target = e.target as HTMLElement;
        // 检查点击的元素是否有data-id属性，或者是否是tooltip的一部分
        const clickedId = target.dataset.id;
        const isTooltip = target.closest('.tooltip');

        // 如果点击的不是有ID的元素，且不是tooltip内部，则关闭tooltip
        if (!clickedId && !isTooltip) {
          setCurrentId('');
        }
      }
    };

    // 添加全局点击事件监听
    document.addEventListener('click', handleDocumentClick);

    // 组件卸载时移除事件监听
    return () => {
      document.removeEventListener('click', handleDocumentClick);
    };
  }, [currentId]);

  // const data = [{
  //   item1: {
  //     name: '三相水泵1',
  //     status: 'normal',
  //     timestamp: '2025-03-10 14:54:24'
  //   },
  //   item2: {
  //     name: '三相水泵2',
  //     status: 'normal',
  //   }
  // },
  // {
  //   // item1: {
  //   //   name: '三相水泵1',
  //   //   status: 'normal',
  //   //   timestamp: '2025-03-10 14:54:24'
  //   // },
  //   item2: {
  //     name: '三相水泵2',
  //     status: 'normal',
  //   }
  // }]

  const data = useMemo(() => {
    const list: any[] = []
    let count = 0
    techList?.forEach((item: any, index: number) => {
      // 1为左，2为右
      // 后续3为右，4为左，再轮回
      // item.devices make id 
      item.devices.forEach((device: any) => {
        const id = Math.random().toString(36).substring(2, 15)
        device.id = id
      })

      console.log('count', item, count)
      if (index % 2 === 0) {
        if (count == 2) {
          list.push({
            item2: item,
          })
        } else {
          list.push({
            item1: item,
          })
        }
      } else {
        const currentIndex = index % 2 - 1
        console.log('currentIndex,', currentIndex, count)
        if (count === 3) {
          list[currentIndex] = {
            ...list[currentIndex],
            item1: item
          }
          count = 0
        } else {
          list[currentIndex] = {
            ...list[currentIndex],
            item2: item
          }
        }
      }
      count++
    })

    return list
  }, [deviceStatus])

  const globalDeviceWithId = useMemo(() => {
    return globalDevice.map((item: any) => {
      return {
        ...item,
        id: Math.random().toString(36).substring(2, 15)
      }
    })
  }, [globalDevice])


  // 添加一个单独的子模块悬停处理函数
  const handleSubmoduleMouseMove = (e: React.MouseEvent, id: string) => {
    e.stopPropagation(); // 阻止事件冒泡
    setCurrentId(id);
    setMousePosition({
      x: e.clientX,
      y: e.clientY
    });
  };

  // 为底部状态栏添加单独的鼠标处理函数
  const handleStatusBarMouseMove = (e: React.MouseEvent, id: string) => {
    e.stopPropagation(); // 阻止事件冒泡
    setCurrentId(id);
    setMousePosition({
      x: e.clientX,
      y: e.clientY
    });
  };

  // 添加子模块的触摸事件处理
  const handleSubmoduleTouchMove = (e: React.TouchEvent, id: string) => {
    e.stopPropagation(); // 阻止事件冒泡
    const touch = e.touches[0];
    setCurrentId(id);
    setMousePosition({
      x: touch.clientX,
      y: touch.clientY
    });
  };

  // 为状态栏添加触摸事件处理
  const handleStatusBarTouchMove = (e: React.TouchEvent, id: string) => {
    e.stopPropagation(); // 阻止事件冒泡
    const touch = e.touches[0];
    setCurrentId(id);
    setMousePosition({
      x: touch.clientX,
      y: touch.clientY
    });
  };

  return (
    <div className="container"
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    >
      <img src="/bg.png" alt="" className='bg' />
      <img src="/main-bg-de.png" className='dec-bg' alt="" />

      <div className='bottom-bar'>
        <div className='left'>

        </div>

        <div className='right'> {globalDeviceWithId?.map((item: any) => {
          return <>
            {createPortal(<div className="tooltip"
              style={{
                left: currentId === item?.id ? mousePosition.x : '-5000px',
                top: currentId === item?.id ? mousePosition.y - 40 : '-5000px',
                transform: 'translate(-50%,-100%)'
              }}
              onClick={(e) => e.stopPropagation()}
            >

              {item?.metricDetails?.map((item: any) => {
                return <div className="tooltip-content">
                  <div className='tooltip-card'>
                    <div className="tooltip-item">
                      <span className="tooltip-label">设备名称</span>
                      <span className="tooltip-value">
                        {item?.metricStatus === 0 ? <span className="status-indicator status-green"></span> : <span className="status-indicator status-red"></span>}
                        {item.metricName}</span>
                    </div>
                    <div className="tooltip-item">
                      <span className="tooltip-label">告警等级</span>
                      <span className="tooltip-value">等级{item.level}</span>
                    </div>
                    <div className="tooltip-item">
                      <span className="tooltip-label">当前值</span>
                      <span className="tooltip-value">{item.value}</span>
                    </div>

                    <div className="tooltip-item">
                      <span className="tooltip-label">更新时间</span>
                      <span className="tooltip-value">{item.lastUpdateTime}</span>
                    </div>
                  </div>
                </div>
              })}

            </div>, document.body)}

            <div
              className='bar'
              onMouseMove={(e) => handleStatusBarMouseMove(e, item?.id)}
              onTouchMove={(e) => handleStatusBarTouchMove(e, item?.id)}
              data-id={item?.id}
              onClick={(e) => e.stopPropagation()}
            >
              {item.status === 0 ?
                <div className='green-circle' data-id={item?.id}></div> :
                <div className='red-circle' data-id={item?.id}></div>
              }
              <div data-id={item?.id}>{item.deviceName}</div>
            </div>
          </>
        })}</div>
      </div>
      <div className='title' style={{ fontSize: 34 }}>数字化实景图（实时大屏）
        {/* <span className='desc'>（实时大屏）</span> */}
      </div>
      <div className='subTitle' style={{ marginTop: -18, color: '#FFF', fontWeight: '600', fontSize: 20, position: 'relative' }}>Digital real-scene image</div>

      <div className="content-wrapper">
        <div className='content' ref={contentRef} style={{
          transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
          transformOrigin: 'top left',
        }}>

          {data.map((item, index) => (
            <RowContent key={index}>
              {index === 0 && <img src="/visonAI.png" alt="" style={{ width: '240px', height: '280px', marginRight: '-40px' }} />}
              {index !== 0 && <div className='visonAI-bg' style={{ width: '240px', height: '280px', marginRight: '-40px' }} />}

              {item.item1 ? <div className="module blue-border">
                <div className='' style={{ fontSize: 20, fontWeight: 'bold' }}>
                  {item.item1?.techName}
                </div>

                {item.item1?.
                  devices?.map((metric: any) => {
                    return <>
                      {createPortal(<div className="tooltip"
                        style={{
                          left: currentId === metric?.id ? mousePosition.x + 10 : '-5000px',
                          top: currentId === metric?.id ? mousePosition.y + 10 : '-5000px'
                        }}
                        onClick={(e) => e.stopPropagation()}
                      >

                        {metric?.metricDetails?.map((item: any) => {
                          if (currentId !== metric?.id) return null
                          return <div className="tooltip-content">
                            <div className='tooltip-card'>
                              <div className="tooltip-item">
                                <span className="tooltip-label">设备名称</span>
                                <span className="tooltip-value">
                                  {item?.metricStatus === 0 ? <span className="status-indicator status-green"></span> : <span className="status-indicator status-red"></span>}
                                  {item.metricName}</span>
                              </div>
                              <div className="tooltip-item">
                                <span className="tooltip-label">告警等级</span>
                                <span className="tooltip-value">等级{item.level}</span>
                              </div>
                              <div className="tooltip-item">
                                <span className="tooltip-label">当前值</span>
                                <span className="tooltip-value">{item.value}</span>
                              </div>
                              <div className="tooltip-item">
                                <span className="tooltip-label">更新时间</span>
                                <span className="tooltip-value">{item.lastUpdateTime}</span>
                              </div>
                            </div>
                          </div>
                        })}

                      </div>, document.body)}



                      <div
                        className="submodule"
                        onMouseMove={(e) => handleSubmoduleMouseMove(e, metric?.id)}
                        onTouchMove={(e) => handleSubmoduleTouchMove(e, metric?.id)}
                        data-id={metric?.id}
                        onClick={(e) => e.stopPropagation()}
                      >
                        {metric?.status === 0 ? <span className="status-indicator status-green"></span> : <span className="status-indicator status-red"></span>}
                        {metric.deviceName}
                        <div className="update-time" data-id={metric?.id}>更新时间: {metric?.lastUpdateTime}</div>
                      </div>
                    </>
                  })}

                {item.item2 && <img className="to-right-arrow" src="./arrow.png" alt="" />}
              </div > : <div className="empty-module">
              </div>}

              {item.item2 ? <div className="module gray-border">
                <div className='' style={{ fontSize: 20, fontWeight: 'bold' }}>
                  {item.item2?.techName}
                </div>

                {item.item2?.devices?.map((metric: any) => {
                  return <>
                    {createPortal(<div className="tooltip"
                      style={{
                        left: currentId === metric?.id ? mousePosition.x + 10 : '-5000px',
                        top: currentId === metric?.id ? mousePosition.y + 10 : '-5000px'
                      }}
                      onClick={(e) => e.stopPropagation()}
                    >

                      {metric?.metricDetails?.map((item: any) => {
                        if (currentId !== metric?.id) return null
                        return <div className="tooltip-content">
                          <div className='tooltip-card'>
                            <div className="tooltip-item">
                              <span className="tooltip-label">设备名称</span>
                              <span className="tooltip-value">
                                {item?.metricStatus === 0 ? <span className="status-indicator status-green"></span> : <span className="status-indicator status-red"></span>}
                                {item.metricName}</span>
                            </div>
                            <div className="tooltip-item">
                              <span className="tooltip-label">告警等级</span>
                              <span className="tooltip-value">等级{item.level}</span>
                            </div>
                            <div className="tooltip-item">
                              <span className="tooltip-label">当前值</span>
                              <span className="tooltip-value">{item.value}</span>
                            </div>
                            <div className="tooltip-item">
                              <span className="tooltip-label">更新时间</span>
                              <span className="tooltip-value">{item.lastUpdateTime}</span>
                            </div>
                          </div>
                        </div>
                      })}
                    </div>, document.body)}

                    <div
                      className="submodule"
                      onMouseMove={(e) => handleSubmoduleMouseMove(e, metric?.id)}
                      onTouchMove={(e) => handleSubmoduleTouchMove(e, metric?.id)}
                      data-id={metric?.id}
                      onClick={(e) => e.stopPropagation()}
                    >
                      {metric?.status === 0 ? <span className="status-indicator status-green"></span> : <span className="status-indicator status-red"></span>}
                      {metric.deviceName}
                      <div className="update-time" data-id={metric?.id}>更新时间: {metric?.lastUpdateTime}</div>
                    </div>
                  </>
                })}
                {index !== data.length - 1 && <img className="to-bottom-arrow" src="./bottom-arrow.png" alt="" />}
              </div> : <div className="empty-module">
              </div>}
            </RowContent>
          ))}
        </div>
      </div>

      <div className="control-panel">
        {/* <div className="zoom-controls">
          <button className="control-btn" onClick={handleZoomIn}>
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
            </svg>
          </button>
          <button className="control-btn" onClick={handleZoomOut}>
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="currentColor" d="M19 13H5v-2h14v2z"/>
            </svg>
          </button>
          <button className="control-btn reset-btn" onClick={handleReset} title="重置视图">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="currentColor" d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/>
            </svg>
          </button>
        </div> */}
        {/* <div className="navigation-controls">
          <button className="control-btn" onClick={() => handleMove('up')}>
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="currentColor" d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/>
            </svg>
          </button>
          <div className="horizontal-controls">
            <button className="control-btn" onClick={() => handleMove('left')}>
              <svg viewBox="0 0 24 24" width="24" height="24">
                <path fill="currentColor" d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z"/>
              </svg>
            </button>
            <button className="control-btn" onClick={() => handleMove('right')}>
              <svg viewBox="0 0 24 24" width="24" height="24">
                <path fill="currentColor" d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
              </svg>
            </button>
          </div>
          <button className="control-btn" onClick={() => handleMove('down')}>
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path fill="currentColor" d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/>
            </svg>
          </button>
        </div> */}
      </div>

    </div>
  );
};

export default DigitalMap;
